<template>
    <div>
        <div class="container">
            <el-main>
                <el-form ref="couponFormRef" :rules="couponFormRules" :model="couponForm" :label-width="formLabelWidth">
                    <el-form-item label="ID" prop="id" v-if="false">
                        <el-input v-model="couponForm.id" class="handle-input mr10" />
                    </el-form-item>
					<!-- 常规信息 -->
					<el-form-item label="券名称" prop="couponName">
                        <el-input v-model="couponForm.couponName" clearable class="handle-input mr10" maxlength="50" show-word-limit/>
                    </el-form-item>
					<el-form-item label="优惠金额" prop="couponAmount">
                        <el-input v-model="couponForm.couponAmount" clearable class="handle-input mr10" maxlength="11" show-word-limit/>
                    </el-form-item>
					<el-form-item label="券分类" prop="couponType">
                        <el-input v-model="couponForm.couponType" class="handle-input mr10" v-if="false"/>
                        <el-select v-model="couponForm.couponType" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in couponTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
					<el-form-item label="使用类型" prop="useType">
                        <el-input v-model="couponForm.useType" class="handle-input mr10" v-if="false"/>
                        <el-select v-model="couponForm.useType" class="handle-select mr10" placeholder="请选择">
                            <el-option v-for="item in couponUseOptions" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                        <span class="mr10 demonstration">通用优惠券，特定优惠券</span>
                    </el-form-item>
					<el-form-item label="特定类型：" prop="specialType">
                        <el-input v-model="couponForm.specialType" clearable class="handle-input mr10" maxlength="6" show-word-limit/>
                        <span class="mr10 demonstration">指向性优惠券，或服务产品，或商品</span>
                    </el-form-item>
					<el-form-item label="有效时间(天)" prop="lengthDays">
                        <el-input v-model="couponForm.lengthDays" clearable class="handle-input mr10" maxlength="3" show-word-limit/>
                    </el-form-item>
                    <el-form-item label="有效时间">
                        <el-date-picker value-format="YYYY-MM-DD" v-model="dateRangeValue" type="daterange" range-separator="To" start-placeholder="开始时间" end-placeholder="到期时间" />
                        <span class="mr10 demonstration">标识该优惠券的使用有效时间周期</span>
                    </el-form-item>
					<el-form-item label="开始时间" prop="startTime" v-if="false">
                        <el-input v-model="couponForm.startTime" clearable class="handle-input mr10" maxlength="6" show-word-limit/>
                    </el-form-item>
					<el-form-item label="到期时间" prop="expTime" v-if="false">
                        <el-input v-model="couponForm.expTime" clearable class="handle-input mr10" maxlength="6" show-word-limit/>
                    </el-form-item>
					<el-form-item label="券状态">
                        <el-input v-model="couponForm.status" class="handle-input mr10" v-if="false"/>
                        <el-switch v-model="couponForm.status" class="handle-switch mr40" placeholder="启用状态"
                             :active-value="2001" :inactive-value="2002" active-text="启用" inactive-text="停用" >
                        </el-switch>
                    </el-form-item>
                </el-form>
            </el-main>
			<el-footer>
				<el-button type="primary" @click="func_onSubmit" plain>保存数据</el-button>
				<el-button type="success" @click="func_onReset" plain>重置表单</el-button>
				<el-button @click="func_closeDialog" plain>取 消</el-button>
			</el-footer>
        </div>
    </div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { findCouponInfoById, addCoupon, saveCoupon, } from "../../../../api/hairmanager/coupon";
import { loadCouponUseEnum, loadCouponTypeEnum, } from "../../../../api/dict";
import { SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE, formLabelWidth, } from "../../../../api/CommonErrorMessage.js";

export default {
    name: "couponForm",
	props:{
		selectValue: Object
	},
	emits: ["CouponData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
        let loadFlg = false;
		/**
         * @name 定义业务表单
         */
        const getInitFormData = () => {
            return {
                dateRangeValue: [],
                couponAmount: 0,
                couponName: '',
                couponType: '',
                expTime: '',
                id: 0,
                infoJson: '',
                lengthDays: 0,
                startTime: '',
                status: 0,
                useType: '',
            }
        };
        /**
         * @name 表单初始化
         */
        const resetCouponForm = () => {
            Object.assign(couponForm, getInitFormData());
            dateRangeValue.value = '';
        };
		const couponForm = reactive(getInitFormData());
		const couponFormRef = ref(null);
        const couponFormRules = {
            linkman: [
                { required: true, message: "请输入联系人姓名", trigger: "blur" },
            ],
            phoneNumber: [
                { required: true, message: "请输入联系人手机号", trigger: "blur" },
            ],
        };
        const dateRangeValue = ref('');
        // =========================================================================================
        const couponUseOptions = ref([]);
        const func_loadCouponUseOptions = () => {
            loadCouponUseEnum().then((res) => {
                res.data.forEach((item) => {
                couponUseOptions.value.push({label: item['label'],value: item['value']});
                });
            });
        };
        const couponTypeOptions = ref([]);
        const func_loadCouponTypeOptions = () => {
            loadCouponTypeEnum().then((res) => {
                res.data.forEach((item) => {
                    couponTypeOptions.value.push({label: item['label'],value: item['value']});
                });
            });
        }; 
        // =========================================================================================
        const provinceOptionVal = ref('');
		const provinceOptions = ref([]);
        const provinceOptionProps = {
            checkStrictly: true,
        }
		const func_loadProvinceOptions = () => {
			loadProvTrees().then((res) => {
				provinceOptions.value = res.data;
			});
		};
		const func_setProvince = () => {
            couponForm['strProvCityAreaCode'] = provinceOptionVal.value.join(',');
		};
        // =========================================================================================
		// 主业务处理 ========================================================================================= START
        // 提交
        const func_onSubmit = () => {
            // 表单校验
            couponFormRef.value.validate((valid) => {
                if (valid) {
                    couponForm['dateRangeValue'] = dateRangeValue.value;
                    if(loadFlg){
                        saveCoupon(couponForm).then((res) => {
							if(res.code != 200) {
								ElMessage.error(res.message);
							} else {
								resetCouponForm();
								ElMessage.success(SUCCESS_EDITDATA_DIALOG_MESSAGE);
								cex.emit('CouponData', {state: 1, load: false, data: []});
							}
						});
                    } else {
                        addCoupon(couponForm).then((res) => {
							if(res.code != 200) {
								ElMessage.error(res.message);
							} else {
								resetCouponForm();
								ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
								cex.emit('CouponData', {state: 1, load: false, data: []});
							}
						});
                    }
                } else {
                    return false;
                }
            });
        };
        // 重置
        const func_onReset = () => {
			resetCouponForm();
        };
		const func_closeDialog = () => {
            cex.emit('CouponData', {state: 1, data: []});
        };
        // 页面初始化
        const func_onload = (v) => {
			if(loadFlg){
				findCouponInfoById(v).then((res) => {
					Object.keys(res.data).forEach((item) => {
                        couponForm[item] = res.data[item];
                    });
                    dateRangeValue.value = [couponForm['strStartTime'],couponForm['strExpTime']];
				});
			} else {
				resetCouponForm();
			}
        }
		// 主业务处理 ========================================================================================= END
        watch(() => props.selectValue, (val) => {
            resetCouponForm();
            let id = val['id'];
            loadFlg = val['load'];
            if(loadFlg) {
			    func_onload(id);
            }
            func_loadCouponUseOptions();
            func_loadCouponTypeOptions();
        }, {deep: true,immediate: true});
        return {
            // 系统变量 =========================================================================================
			formLabelWidth, couponForm, couponFormRef, couponFormRules, dateRangeValue, couponUseOptions, couponTypeOptions,
            // 主调用方法 =========================================================================================  
            func_onload, getInitFormData, resetCouponForm, func_onSubmit, func_onReset, func_closeDialog, func_loadCouponUseOptions, func_loadCouponTypeOptions,
            // =========================================================================================
            provinceOptions, provinceOptionProps, provinceOptionVal, func_setProvince, func_loadProvinceOptions,
        };
    },
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 300px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style>